package com.qd.system.service.station;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.excel.ExcelExport;
import com.cdqidi.excel.util.ExportPage;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.sys.domain.entity.station.PersonStationOrgDTO;
import com.qd.common.sys.domain.entity.station.PersonStationOrgListDTO;
import com.qd.system.mapper.PersonStationOrgMapper;
import com.qd.system.model.PersonStationOrg;
import com.qd.system.service.org.OrgService;
import com.qd.system.service.person.PersonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

import static java.util.stream.Collectors.toList;

/**
 * 人员岗位组织
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class PersonStationOrgService extends BaseService<PersonStationOrgMapper, PersonStationOrg> {

    private static final String PREFIX_ID = "sys_person_station_org_personStationId_{0}";
    private static final String PREFIX_UNIQUE_SYS_PERSON = "sys_person_station_org_stationId_{0}_personId_{1}_orgId_{2}";

    private final RedisTemplateUtil<PersonStationOrg> redisTemplateUtil;
    private final OrgService orgService;
    private final PersonService personService;
    private final StationSetService stationSetService;
    @Resource
    private HttpServletResponse response;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public PersonStationOrgDTO save(PersonStationOrgDTO dto) {
        checkMb(dto);
        final PersonStationOrg model = dtoToModel(dto);
        try {
           if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public PersonStationOrgDTO update(PersonStationOrgDTO dto) {
        checkMb(dto);
        final PersonStationOrg oldModel = Optional.ofNullable(getById(dto.getPersonStationId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final PersonStationOrg model = dtoToModel(dto);
         try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(oldModel);
            oldModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<PersonStationOrg> mList) throws ApiException {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<PersonStationOrg> mList) {
        final List<String> ids = mList.stream().map(PersonStationOrg::getPersonStationId).collect(toList());
        final List<PersonStationOrg> dbList = checkIds(ids);
        try {

            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(dbList);
            dbList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param personStationId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String personStationId) {
        final PersonStationOrg model = Optional.ofNullable(getById(personStationId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(personStationId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        List<PersonStationOrg> dbList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(dbList);
            dbList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(PersonStationOrgDTO dto) {
        final QueryWrapper<PersonStationOrg> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param personStationId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String personStationId) {
        boolean exists = false;
        if (StringUtils.hasLength(personStationId)) {
            final PersonStationOrg model = getById(personStationId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param personStationId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public PersonStationOrg getById(String personStationId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, personStationId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(personStationId), PersonStationOrg.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param personStationId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public PersonStationOrgDTO getByIdDto(String personStationId) {
        return Optional.ofNullable(getById(personStationId)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public PersonStationOrg getOne(PersonStationOrgDTO dto) {
        final QueryWrapper<PersonStationOrg> queryWrapper = createQueryWrapper(dto);
        PersonStationOrg model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public PersonStationOrgDTO getOneDto(PersonStationOrgDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<PersonStationOrg> getList(PersonStationOrgDTO dto) {
        final QueryWrapper<PersonStationOrg> queryWrapper = createQueryWrapper(dto);
        final List<PersonStationOrg> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<PersonStationOrgDTO> getListDto(PersonStationOrgDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<PersonStationOrgDTO> page(Page<PersonStationOrg> page, PersonStationOrgDTO dto) {
        final QueryWrapper<PersonStationOrg> queryWrapper = createQueryWrapper(dto, "per.");
        final IPage<PersonStationOrgDTO> iPage = baseMapper.page(page, queryWrapper);
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 导出Excel
     *
     * @param query 查询条件
     */
    @Transactional(readOnly = true)
    public void export(PersonStationOrgDTO query) {
        final ExportPage<PersonStationOrg, PersonStationOrgDTO> exportPage = new ExportPage<>();
        try{
            final List<PersonStationOrgDTO> list = exportPage.getAllForPage(page -> page(page, query).getRecords());
            try {
                ExcelExport.downloadExcel(response, PersonStationOrgDTO.class, () -> list);
            } catch (IOException e) {
                log.error("导出失败", e);
                throw new ApiException("导出失败");
            }
        }finally {
            exportPage.freeData();
        }
    }

    /**
     * 根据唯一性索引获得数据
     * <p>
     * param stationId
     * param personId
     * param orgId
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public PersonStationOrg getUniqueByStationIdAndPersonIdAndOrgId(String stationId, String personId, String orgId) {
        final QueryWrapper<PersonStationOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("station_id", stationId);
        queryWrapper.eq("person_id", personId);
        queryWrapper.eq("org_id", orgId);
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_SYS_PERSON, stationId, personId, orgId);
        final PersonStationOrg model = redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getOne(queryWrapper, false), PersonStationOrg.class);
        queryWrapper.clear();
        return model;
    }

    @Transactional(readOnly = true)
    public void checkMb(PersonStationOrgDTO dto) {
        orgService.checkId(dto.getOrgId());
        personService.checkId(dto.getPersonId());
        stationSetService.checkId(dto.getStationId());
        checkUnique(dto);
    }

    /**
     * 验证唯一性索引
     *
     * @param dto 页面对象
     */
    @Transactional(readOnly = true)
    public void checkUnique(PersonStationOrgDTO dto) {
        PersonStationOrg model = getUniqueByStationIdAndPersonIdAndOrgId(dto.getStationId(), dto.getPersonId(), dto.getOrgId());
        if (null != model) {
            checkUnique(dto, model);
        }
    }

    /**
     * 验证唯一性索引
     *
     * @param dto   页面对象
     * @param model 根据约束字段查询出来的数据库对象
     */
    private void checkUnique(PersonStationOrgDTO dto, PersonStationOrg model) {
        if (!StringUtils.hasLength(dto.getPersonStationId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
        if (!dto.getPersonStationId().equals(model.getPersonStationId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(PersonStationOrg model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getPersonStationId()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_SYS_PERSON, model.getStationId(), model.getPersonId(), model.getOrgId()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<PersonStationOrg> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getPersonStationId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
        List<String> uniqueIds = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_SYS_PERSON, model.getStationId(), model.getPersonId(), model.getOrgId())).collect(toList());
        if (!uniqueIds.isEmpty()) {
            redisTemplateUtil.deleteByKey(uniqueIds);
            uniqueIds.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public PersonStationOrgDTO modelToDto(PersonStationOrg model) {
        if (null == model) {
            return null;
        }
        final PersonStationOrgDTO dto = new PersonStationOrgDTO();
        dto.setPersonStationId(model.getPersonStationId());
        dto.setOrgId(model.getOrgId());
        dto.setStationId(model.getStationId());
        dto.setPersonId(model.getPersonId());
        dto.setAddTime(model.getAddTime());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public PersonStationOrg dtoToModel(PersonStationOrgDTO dto) {
        if (null == dto) {
            return null;
        }
        final PersonStationOrg model = new PersonStationOrg();
        model.setPersonStationId(dto.getPersonStationId());
        model.setOrgId(dto.getOrgId());
        model.setStationId(dto.getStationId());
        model.setPersonId(dto.getPersonId());
        model.setAddTime(dto.getAddTime());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(PersonStationOrgDTO dto) {
        dto.setOrgIdDisplay(orgService.idToDisplay(dto.getOrgId()));
        dto.setStationIdDisplay(stationSetService.idToDisplay(dto.getStationId()));
        dto.setPersonIdDisplay(personService.idToDisplay(dto.getPersonId()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<PersonStationOrgDTO> modelToDtoList(List<PersonStationOrg> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<PersonStationOrg> dtoToModelList(List<PersonStationOrgDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<PersonStationOrg> createQueryWrapper(PersonStationOrgDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<PersonStationOrg> createQueryWrapper(PersonStationOrgDTO dto, String tableAlias) {
        final QueryWrapper<PersonStationOrg> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
             if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getOrgId())) {
                queryWrapper.eq(tableAlias + "org_id", dto.getOrgId());
            }
            if (StringUtils.hasLength(dto.getStationId())) {
                queryWrapper.eq(tableAlias + "station_id", dto.getStationId());
            }
            if (StringUtils.hasLength(dto.getPersonId())) {
                queryWrapper.eq(tableAlias + "person_id", dto.getPersonId());
            }
            if (StringUtils.hasLength(dto.getBeginTime())) {
                queryWrapper.apply("date_format(" + tableAlias + "add_time,'%Y-%m-%d') >= {0}", dto.getBeginTime());
            }
            if (StringUtils.hasLength(dto.getEndTime())) {
                queryWrapper.apply("date_format(" + tableAlias + "add_time,'%Y-%m-%d') <= {0}", dto.getEndTime());
            }
            if (StringUtils.hasLength(dto.getOrgName())) {
                queryWrapper.like("so.org_name", dto.getOrgName());
            }
            if (StringUtils.hasLength(dto.getStationCode())) {
                queryWrapper.eq("s.station_code", dto.getStationCode());
            }
            if (StringUtils.hasLength(dto.getStationName())) {
                queryWrapper.like("s.station_name", dto.getStationName());
            }
            if (StringUtils.hasLength(dto.getPersonName())) {
                queryWrapper.like("p.person_name", dto.getPersonName());
            }
            if (StringUtils.hasLength(dto.getIdCard())) {
                queryWrapper.eq("p.id_card", dto.getIdCard());
            }
            if (StringUtils.hasLength(dto.getMobile())) {
                queryWrapper.eq("p.phone", dto.getMobile());
            }
        }
        queryWrapper.orderByAsc("st.idx");
        queryWrapper.orderByAsc("so.order_num");
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<PersonStationOrg> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<PersonStationOrg> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(PersonStationOrg::getPersonStationId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(PersonStationOrgListDTO dto) {
        orgService.checkId(dto.getOrgId());
        personService.checkIds(dto.getPersonList());
        stationSetService.checkId(dto.getStationId());
        LocalDateTime now = LocalDateTime.now();
        List<PersonStationOrg> addList = new ArrayList<>(dto.getPersonList().size());
        for (String personId : dto.getPersonList()) {
            PersonStationOrg model = getUniqueByStationIdAndPersonIdAndOrgId(dto.getStationId(), personId, dto.getOrgId());
            if (null == model) {
                model = new PersonStationOrg();
                model.setStationId(dto.getStationId())
                        .setPersonId(personId)
                        .setOrgId(dto.getOrgId())
                        .setAddTime(now);
                addList.add(model);
            }
        }
        if (!addList.isEmpty()) {
            saveBatch(addList);
        }
    }
}